/**
 * 动画配置和工具函数
 * 
 * 设计原则：
 * 1. 专业克制 - 金融系统需要专业感，避免过度动画
 * 2. 性能优先 - 使用 GPU 加速的属性（transform, opacity）
 * 3. 可访问性 - 尊重用户的 prefers-reduced-motion 设置
 * 4. 一致性 - 统一的缓动函数和时长
 */

// ==================== 动画时长配置 ====================
export const DURATION = {
  instant: 0,           // 即时（禁用动画时使用）
  fast: 150,            // 快速：按钮、悬停效果
  normal: 300,          // 正常：卡片、下拉菜单
  slow: 500,            // 慢速：页面过渡、大型组件
  tooltip: 200,         // Tooltip 专用
  skeleton: 1500,       // 骨架屏脉动
} as const

// ==================== 缓动函数配置 ====================
export const EASING = {
  // 标准缓动
  linear: 'linear',
  ease: 'ease',
  easeIn: 'ease-in',
  easeOut: 'ease-out',
  easeInOut: 'ease-in-out',
  
  // 自定义贝塞尔曲线
  smooth: 'cubic-bezier(0.4, 0, 0.2, 1)',          // 平滑（Material Design）
  snappy: 'cubic-bezier(0.4, 0, 0.6, 1)',          // 快速响应
  bounce: 'cubic-bezier(0.68, -0.55, 0.265, 1.55)', // 轻微弹跳
  spring: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)', // 弹簧效果
} as const

// ==================== 常用动画类名 ====================
export const ANIMATION_CLASSES = {
  // 淡入淡出
  fadeIn: 'animate-in fade-in',
  fadeOut: 'animate-out fade-out',
  
  // 滑动
  slideInFromTop: 'animate-in slide-in-from-top',
  slideInFromBottom: 'animate-in slide-in-from-bottom',
  slideInFromLeft: 'animate-in slide-in-from-left',
  slideInFromRight: 'animate-in slide-in-from-right',
  
  slideOutToTop: 'animate-out slide-out-to-top',
  slideOutToBottom: 'animate-out slide-out-to-bottom',
  slideOutToLeft: 'animate-out slide-out-to-left',
  slideOutToRight: 'animate-out slide-out-to-right',
  
  // 缩放
  scaleIn: 'animate-in zoom-in',
  scaleOut: 'animate-out zoom-out',
  
  // 组合动画
  popIn: 'animate-in fade-in zoom-in-95',          // 弹出（淡入+放大）
  popOut: 'animate-out fade-out zoom-out-95',      // 弹出消失
  
  // 骨架屏脉动
  pulse: 'animate-pulse',
  
  // 旋转（加载）
  spin: 'animate-spin',
} as const

// ==================== Tailwind 动画配置建议 ====================
/**
 * 在 tailwind.config.ts 中添加以下配置：
 * 
 * theme: {
 *   extend: {
 *     keyframes: {
 *       "slide-up": {
 *         "0%": { transform: "translateY(10px)", opacity: "0" },
 *         "100%": { transform: "translateY(0)", opacity: "1" },
 *       },
 *       "slide-down": {
 *         "0%": { transform: "translateY(-10px)", opacity: "0" },
 *         "100%": { transform: "translateY(0)", opacity: "1" },
 *       },
 *       "scale-in": {
 *         "0%": { transform: "scale(0.95)", opacity: "0" },
 *         "100%": { transform: "scale(1)", opacity: "1" },
 *       },
 *       "shimmer": {
 *         "0%": { backgroundPosition: "-1000px 0" },
 *         "100%": { backgroundPosition: "1000px 0" },
 *       },
 *     },
 *     animation: {
 *       "slide-up": "slide-up 0.3s cubic-bezier(0.4, 0, 0.2, 1)",
 *       "slide-down": "slide-down 0.3s cubic-bezier(0.4, 0, 0.2, 1)",
 *       "scale-in": "scale-in 0.2s cubic-bezier(0.4, 0, 0.2, 1)",
 *       "shimmer": "shimmer 2s infinite linear",
 *     },
 *   },
 * }
 */

// ==================== React 动画 Hook ====================
/**
 * 检查用户是否偏好减少动画
 */
export function usePrefersReducedMotion(): boolean {
  if (typeof window === 'undefined') return false
  
  const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)')
  return mediaQuery.matches
}

/**
 * 获取考虑用户偏好的动画时长
 */
export function getAnimationDuration(duration: keyof typeof DURATION): number {
  if (typeof window !== 'undefined') {
    const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches
    return prefersReduced ? DURATION.instant : DURATION[duration]
  }
  return DURATION[duration]
}

// ==================== 交互动画预设 ====================
/**
 * 按钮悬停/按下效果
 */
export const BUTTON_ANIMATION = {
  hover: 'transition-all duration-150 hover:scale-105 active:scale-95',
  subtle: 'transition-colors duration-150',
  glow: 'transition-all duration-300 hover:shadow-lg hover:shadow-accent/50',
} as const

/**
 * 卡片动画
 */
export const CARD_ANIMATION = {
  hover: 'transition-all duration-300 hover:shadow-lg hover:-translate-y-1',
  subtle: 'transition-shadow duration-300 hover:shadow-md',
  border: 'transition-all duration-300 hover:border-accent',
  glow: 'transition-all duration-300 hover:shadow-xl hover:shadow-accent/20',
} as const

/**
 * 输入框动画
 */
export const INPUT_ANIMATION = {
  focus: 'transition-all duration-200 focus:ring-2 focus:ring-accent focus:border-accent',
  error: 'transition-all duration-200 border-destructive focus:ring-destructive',
} as const

/**
 * 列表项动画（交错）
 */
export const LIST_ANIMATION = {
  stagger: (index: number, baseDelay = 50) => ({
    style: {
      animationDelay: `${index * baseDelay}ms`,
    },
    className: 'animate-in fade-in slide-in-from-bottom-2',
  }),
} as const

/**
 * 数字滚动动画（用于数据更新）
 */
export function animateNumber(
  element: HTMLElement,
  from: number,
  to: number,
  duration: number = DURATION.normal,
  formatter?: (value: number) => string
) {
  const start = performance.now()
  const delta = to - from
  
  function update(currentTime: number) {
    const elapsed = currentTime - start
    const progress = Math.min(elapsed / duration, 1)
    
    // 使用 easeOutExpo 缓动
    const eased = progress === 1 ? 1 : 1 - Math.pow(2, -10 * progress)
    const current = from + delta * eased
    
    element.textContent = formatter ? formatter(current) : current.toFixed(0)
    
    if (progress < 1) {
      requestAnimationFrame(update)
    }
  }
  
  requestAnimationFrame(update)
}

/**
 * 百分比变化动画（带颜色过渡）
 */
export function animatePercentChange(
  element: HTMLElement,
  from: number,
  to: number,
  duration: number = DURATION.normal
) {
  const isPositive = to >= 0
  
  // 数字动画
  animateNumber(element, from, to, duration, (value) => {
    const sign = value >= 0 ? '+' : ''
    return `${sign}${value.toFixed(2)}%`
  })
  
  // 颜色过渡
  element.classList.add('transition-colors', 'duration-300')
  element.classList.remove('text-success', 'text-destructive')
  element.classList.add(isPositive ? 'text-success' : 'text-destructive')
}

// ==================== 页面过渡动画 ====================
export const PAGE_TRANSITION = {
  initial: { opacity: 0, y: 20 },
  animate: { opacity: 1, y: 0 },
  exit: { opacity: 0, y: -20 },
  transition: {
    duration: 0.3,
    ease: EASING.smooth,
  },
} as const

// ==================== 骨架屏动画 ====================
export const SKELETON_ANIMATION = {
  className: 'animate-pulse bg-gradient-to-r from-muted via-muted/50 to-muted',
  shimmer: 'relative overflow-hidden before:absolute before:inset-0 before:-translate-x-full before:animate-shimmer before:bg-gradient-to-r before:from-transparent before:via-white/10 before:to-transparent',
} as const

// ==================== Toast 通知动画 ====================
export const TOAST_ANIMATION = {
  enter: 'animate-in slide-in-from-top-full fade-in',
  exit: 'animate-out slide-out-to-right-full fade-out',
  duration: DURATION.normal,
} as const

// ==================== 模态框动画 ====================
export const MODAL_ANIMATION = {
  overlay: {
    enter: 'animate-in fade-in',
    exit: 'animate-out fade-out',
  },
  content: {
    enter: 'animate-in fade-in zoom-in-95 slide-in-from-bottom-2',
    exit: 'animate-out fade-out zoom-out-95 slide-out-to-bottom-2',
  },
  duration: DURATION.normal,
} as const

// ==================== 工具函数 ====================
/**
 * 延迟执行（用于交错动画）
 */
export const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

/**
 * 创建交错延迟
 */
export function createStaggerDelay(index: number, baseDelay: number = 50): string {
  return `${index * baseDelay}ms`
}

/**
 * 组合动画类名
 */
export function combineAnimations(...animations: string[]): string {
  return animations.filter(Boolean).join(' ')
}


